package com.demo.kotlin.ui.home

import android.os.Bundle
import android.widget.TextView
import com.blankj.utilcode.util.SpanUtils
import com.demo.kotlin.R
import com.demo.kotlin.databinding.FragmentHomeBinding
import com.demo.kotlin.ui.main.MainTabFragment
import com.puhui.lib.base.mvp.IPresenter
import com.puhui.lib.utils.TimeUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.text.SimpleDateFormat
import java.util.*

class HomeFragment : MainTabFragment<FragmentHomeBinding, IPresenter>() {

    private var subscribe: Disposable? = null
    private var currentSportsTime = 0

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun initView(savedInstanceState: Bundle?) {

        mContentView.currentTimeTv.text = getTime()
//        sportTimeTv.setText(TimeUtils.formatDuring(currentSportsTime));
        //        sportTimeTv.setText(TimeUtils.formatDuring(currentSportsTime));
        setSportTimeData(mContentView.sportTimeTv, 0, 0)

        subscribe = Observable.interval(1, java.util.concurrent.TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Consumer<Long?> {
                @Throws(Exception::class)
                override fun accept(aLong: Long?) {
                    mContentView.currentTimeTv.text = getTime()
                    currentSportsTime += 1000

//                        sportTimeTv.setText(TimeUtils.formatDuring(currentSportsTime * 1000));
                    setSportTimeData(
                        mContentView.sportTimeTv,
                        TimeUtils.getMinutesOfTime(currentSportsTime.toLong()),
                        TimeUtils.getSecondsOfTime(currentSportsTime.toLong())
                    )
                }
            })
    }

    private fun setSportTimeData(sportTimeTv: TextView, minutes: Int, seconds: Int) {
        SpanUtils.with(sportTimeTv)
            .append(minutes.toString() + "")
            .setFontSize(100, true)
            .append(" : ")
            .append(seconds.toString() + "")
            .setFontSize(100, true)
            .append(" S")
            .create()
    }

    private fun getTime(): String? {
        return TimeUtils.getTime(System.currentTimeMillis(), SimpleDateFormat("HH:mm:ss", Locale.CHINA))
    }

    override fun onDestroy() {
        subscribe?.dispose()
        super.onDestroy()
    }
}